from itertools import *
import Image
import ImageDraw
import ImageEnhance

#from itertools
def grouper(n, iterable, padvalue=None):
    "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
    return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)



def isRowBlank( img, row ):
    for i in range(img.size[0] ):
        if (img.getpixel( (i, row) ) != (192, 192, 192) ):
            return False

    return True

def isColumnBlank( img, col ):
    for i in range(img.size[1] ):
        if (img.getpixel( ( col, i) ) != (192, 192, 192) ):
            return False

    return True

mascotImg = Image.open( "tetris.PNG" )
mdraw = ImageDraw.Draw( mascotImg )

print mascotImg.format, mascotImg.size

# remove red/blue markup
for j in range( mascotImg.size[1] ):
    for i in range( mascotImg.size[0] ):
        if ( mascotImg.getpixel( (i, j) ) == ( 255, 0, 0 )
             or mascotImg.getpixel( (i, j) ) == ( 0, 0, 255 ) ):
            
            mdraw.point( (i, j), fill=(192,192, 192) )

mascotNames = [
    "yoshi", "cloudbaby",
    "dogthing", "bird",
    "frog", "blarg",
    "fish", 
    "penguin",   
    "koopa",
    "plant",
    "wizard",
    "bowser" ]


maxW = 0
maxH = 0

animSprites = []

rowStart = ( 6, 17 )
for ndx, name in izip( count(0), mascotNames ):

    # fixes
    if ndx==8:
        # koopa
        rowStart = ( 7, rowStart[1] )
    elif ndx==10:
        # wizard dude
        rowStart = ( 5, rowStart[1] )    

    #=============================
    print ndx, name, rowStart
    currRow = (rowStart[0], rowStart[1] )


    # Profile image
    imgProfile = mascotImg.crop( ( currRow[0], currRow[1],
                                   currRow[0]+24,
                                   currRow[1]+24 ) )

    imgProfile = imgProfile.resize( (48, 48 ) )
    #imgProfile.save( "mascots/%02d_%s_profile.png" % ( ndx,name) )

    imgUnsel = Image.open( "button_unsel.png" );
    imgSel = Image.open( "button_sel.png" );

    imgSel.paste( imgProfile, (3, 3) )
    imgSel.save( "mascots/%02d_%s_profile_sel.png" % ( ndx,name) )

    contrast = ImageEnhance.Contrast( imgProfile )

    imgUnsel.paste( contrast.enhance( 0.5 ), (3, 3) )
    imgUnsel.save( "mascots/%02d_%s_profile.png" % ( ndx,name) )

    
    #=============================
    # get the sprites for this row
    ymin = currRow[1]
    while not isRowBlank( mascotImg, ymin ):
        ymin -= 1

    mdraw.line( (0, ymin, mascotImg.size[0]-1,ymin), fill=(192,255,192) )
    
    ymax = currRow[1]
    while not isRowBlank( mascotImg, ymax ):
        ymax += 1
        
    mdraw.line( (0, ymax, mascotImg.size[0]-1,ymax), fill=(192,255,192) )

    maxH = max( maxH, ymax - ymin )

    spriteBBox = []
    xmin = rowStart[0]+25

    imgRowSprites = mascotImg.crop( ( rowStart[0]+25, ymin+1,
                                      mascotImg.size[0], ymax ) )

    divs = []
    toggle = True
    for xval in range( imgRowSprites.size[0] ):
        blank = isColumnBlank( imgRowSprites, xval )
        if (blank != toggle):
            toggle = blank
            divs.append( xval )

    #rdraw = ImageDraw.Draw( imgRowSprites )
    #for xd in divs:
    #    rdraw.line( (xd, 0, xd, imgRowSprites.size[1]), fill=(192,255,192) )


    for xx in grouper( 2, divs ):
    #    rdraw.line( (xx[0], imgRowSprites.size[1]/2,
    #                 xx[1], imgRowSprites.size[1]/2), fill=(192,255,192) )
        maxW = max( maxW, xx[1]-xx[0] )

    frameNum = 0
    for xx in grouper( 2, divs ):
        imgSprite = imgRowSprites.crop( ( xx[0], 0,
                                          xx[1], imgRowSprites.size[1] ) )

        imgSprite = imgSprite.resize( (imgSprite.size[0]*4, imgSprite.size[1]*4 ) )

        imgSprite2 = Image.new( "RGB", (150, 150), (192,192,192) )

        imgSprite2.paste( imgSprite,
                          ( 75 - imgSprite.size[0]/2,
                            132-imgSprite.size[1] ) )

        spriteName = ("mascots/%s_frame%02d.png" %
                                (name, frameNum ) )
        imgSprite2.save( spriteName )
        animSprites.append( spriteName )        
        
        frameNum += 1
        
    imgRowSprites.save( "mascots/%02d_%s_dbgSprites.png" % (ndx, name) )

    

    #=============================
    # find the next rowStart
    rowStart = ( 6, rowStart[1]+25 )

    while ( ( mascotImg.getpixel( rowStart )[0] == 192)
         and ( mascotImg.getpixel( (rowStart[0]+1, rowStart[1]) )[0] == 192)):

        #print rowStart, mascotImg.getpixel( rowStart )
        rowStart = (rowStart[0], rowStart[1]+1)

        if (rowStart[1] > 493):
            break

# done with images
mascotImg.save( "mascot2.png" )
print "Max Size", 4*maxW, 4*maxH

# save a .qrc file
fp = open('anims.qrc', "wt" )
fp.write('<RCC>\n\t<qresource prefix="/anims">\n')

for spriteName in animSprites:
    fp.write("\t\t<file>" + spriteName + "</file>\n" )

fp.write('\t</qresource>\n</RCC>\n' )
fp.close()
         
